import { ComponentWithStore } from "mobx-miniprogram-bindings";
import { userStore } from "../../../../stores/userstore";
import { reqUploadFile,reqSave } from "../../../../api/login";

ComponentWithStore({
  storeBindings: {
    store: userStore,
    fields: ["userInfo"],
    actions: ["setUserInfo"]
  },

  // 页面的初始数据
  data: {
    isShowPopup: false, // 控制更新用户昵称的弹框显示与否
  },

  methods: {
    async onChooseAvatar(e) {
      const { avatarUrl } = e.detail;

      const { data } = await reqUploadFile(avatarUrl, "file");
      this.setData({
        "userInfo.headimgurl": data.data,
      });
    },

    // 显示修改昵称弹框
    onUpdateNickName() {
      this.setData({
        isShowPopup: true,
        "userInfo.nickname":this.data.userInfo.nickname
      });
    },

    // 弹框取消按钮
    cancelForm() {
      this.setData({
        isShowPopup: false,
      });
    },

    getNickName(event) {
      // console.log('弹窗确定=》',event);
      const { nickname } = event.detail.value;
      this.setData({
        "userInfo.nickname": nickname,
        isShowPopup: false,
      });
    },

    async save() {
      const res = await reqSave(this.data.userInfo)
      
      if(res.data.code === 200) {
        wx.setStorageSync("userInfo",this.data.userInfo)
        this.setUserInfo(this.data.userInfo)
        wx.showToast({title:'用户信息更新成功'})
      }
    }
  },
});
